﻿<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>readonly()方法</title>
</head>
<body>
<div id="app">
    <p>姓名: {{ state.name }}</p>
    <p>年龄: {{ state.attr.age }}</p>
    <p>身高: {{ state.attr.height }}</p>
    <button @click="myFn">尝试修改只读数据</button>
    <p>查看控制台输出</p>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
    const { createApp, readonly } = Vue;
    
    const app = createApp({
        data() {
            return {
                // readonly:用于创建一个只读的数据，并且是递归只读
                state: readonly({name: '张三', attr: {age: 28, height: 1.88}})
            }
        },
        methods: {
            myFn() {
                try {
                    // 尝试修改只读数据，这不会生效
                    this.state.name = '李四';
                    this.state.attr.age = 29;
                    this.state.attr.height = 1.89;
                    console.log('尝试修改后的数据:', this.state);
                } catch (error) {
                    console.error('修改只读数据时出错:', error);
                }
            }
        }
    });
    
    app.mount('#app');
</script>
</body>
</html>
